package com.android.functionmanagement.ui;

import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.SwitchPreference;

import com.android.functionmanagement.BasePreferenceActivity;
import com.android.functionmanagement.globle.ConstantGloble;
import com.android.functionmanagement.util.DeviceUtils;
import com.android.functionmanagement.util.SharedPreferencesUtils;
import com.uwatch.helowin.R;

public class GatherPeriodActivity extends BasePreferenceActivity implements
		OnPreferenceClickListener {

	private static final String KEY_GATHER_DATA_SWITCH = "gather_data_switch";
	private static final String KEY_GATHER_DATA_PERIOD = "gather_data_picker_period";
	private SwitchPreference mGatherDataSwitch;
	private Preference mGatherDataPeriod;
	private boolean isOpenGatherData;
	private int gatherPeriod;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.gather_data_settings);
		mGatherDataSwitch = (SwitchPreference) findPreference(KEY_GATHER_DATA_SWITCH);
		mGatherDataPeriod = findPreference(KEY_GATHER_DATA_PERIOD);
		mGatherDataSwitch.setOnPreferenceClickListener(this);
		getPreferenceScreen().removePreference(mGatherDataSwitch);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		isOpenGatherData = (Boolean) SharedPreferencesUtils.getParam(this,
				ConstantGloble.GATHER_DATA_SWITCH,
				ConstantGloble.DEFAULT_GATHER_DATA_STATUS);
		try {
			gatherPeriod = Integer.parseInt(SharedPreferencesUtils.getParam(this,
					ConstantGloble.GATHER_DATA_PERIOD,
					ConstantGloble.DEFAULT_GATHER_DATA_PERIOD).toString());
		} catch (NumberFormatException e) {
			// TODO: handle exception
		}

		mGatherDataSwitch.setChecked(isOpenGatherData);
		mGatherDataPeriod.setSummary(getString(R.string.gather_period_of_time,
				gatherPeriod));
		super.onResume();
	}


	@Override
	public boolean onPreferenceClick(Preference preference) {
		// TODO Auto-generated method stub
		if (preference == mGatherDataSwitch) {
			SharedPreferencesUtils.setParam(GatherPeriodActivity.this,
					ConstantGloble.GATHER_DATA_SWITCH,
					mGatherDataSwitch.isChecked());
			if (!mGatherDataSwitch.isChecked())
				DeviceUtils.cancelAlarm(this,
						ConstantGloble.ALARM_ACTION_GATHER_DATA,
						ConstantGloble.ALARM_REQUEST_GATHER_DATA);
		}
		return false;
	}
}
